package net.wantongtech.xa.uploadbasicinfo.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.google.common.collect.Lists;
import com.wtkj.vo.RandomGUID;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.CancelCardRefundDao;
import net.wantongtech.xa.uploadbasicinfo.vo.RefundExcelModel;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 读取监听器
 *
 * @author MaShibo
 * 日期 :  2020/1/3
 */
@Slf4j
public class RefundModelListener extends AnalysisEventListener<RefundExcelModel> {

    @Getter
    private List<RefundExcelModel> refundExcelModelList = Lists.newArrayList();

    private final CancelCardRefundDao cancelCardRefundDao;

    private final String fileName;

    public RefundModelListener(CancelCardRefundDao cancelCardRefundDao, String fileName) {
        this.cancelCardRefundDao = cancelCardRefundDao;
        this.fileName = fileName;
    }

    @Override
    public void invoke(RefundExcelModel data, AnalysisContext context) {
        data.setId(new RandomGUID().toString());
        data.setFileName(fileName);
        refundExcelModelList.add(data);
    }

    @Override
    public synchronized void doAfterAllAnalysed(AnalysisContext context) {
        log.info("解析完成");
        if (!refundExcelModelList.isEmpty()) {
            log.info("共有{}条数据待插入", refundExcelModelList.size());
            List<RefundExcelModel> errorPhoneNoList = refundExcelModelList.stream()
                    .filter(v -> StringUtils.length(v.getPhoneNo()) > 20)
                    .collect(Collectors.toList());
            log.info(errorPhoneNoList.toString());
            try {
                cancelCardRefundDao.batchInsertRefundInfo(refundExcelModelList);
            } finally {
                refundExcelModelList.clear();
            }
        }
    }
}
